<?php
namespace Api\Controller;
use Think\Controller;
use Api\Model\LoginModel;
class LoginController extends Controller {

    //登录验证
    public function index(){
		//解决跨域
		echoHeader();
       $username=I('post.phone','');
	   $password=I('post.password','','md5');
	   $lng=I('post.lng');     //经度
	   $lat=I('post.lat');     //纬度
	   $role=I('post.role','','int');     //角色 1业主2师傅

        $yanzh=12345;
		if(!$username || !$password){
			$data=array('err_code'=>1101,'err_msg'=>'密码或者账号不能为空');
			$this->ajaxReturn($data,'JSON');
		}

	    //验证码
		if(!$yanzh){
		   $data=array('err_code'=>1105,'err_msg'=>'验证码错误');
		   $this->ajaxReturn($data,'JSON');
		}

		//验证用户合法性
		$userWhere['u.phone']=$username;
		$user=M('user u')->where($userWhere)->field('u.user_face,u.login_password,u.user_id,u.user_name,u.phone,u.online,u.role,u.total,u.frozen_total,u.is_real,u.identity,u.is_listen,u.user_status,u.master_status,u.random')->limit(1)->select();
 		if(empty($user)){
			$data=array('err_code'=>1106,'err_msg'=>'用户名不存在');
			$this->ajaxReturn($data,'JSON');
		}

		if($role==2 && $user[0]['is_real']==0){
			$data=array('err_code'=>1107,'err_msg'=>'师傅未认证');
			$this->ajaxReturn($data,'JSON');
		}

		if($role==2 && $user[0]['is_real']==2){
			$data=array('err_code'=>1108,'err_msg'=>'实名认证中');
			$this->ajaxReturn($data,'JSON');
		}
		if($role==2 && $user[0]['is_real']==3){
			$data=array('err_code'=>1109,'err_msg'=>'审核不通过');
			$this->ajaxReturn($data,'JSON');
		}

		if($role==1 &&($user[0]['user_status']==1 || $user[0]['user_status']==3 )){
			$data=array('err_code'=>1102,'err_msg'=>'已被锁定');
			$this->ajaxReturn($data,'JSON');
		}

		if($role==2 &&($user[0]['master_status']==1 || $user[0]['master_status']==3 )){
			$data=array('err_code'=>1102,'err_msg'=>'已被锁定');
			$this->ajaxReturn($data,'JSON');
		}


		$password=md5($password.$user[0]['random']);
        unset($user[0]['random']);
		if($password===$user[0]['login_password']){
			session('user',$username);
			unset($user[0]['login_password']);
			//存储key
			$key=$username.C('KEY_POSTFIX').time();
			$redis=S(array('type'=>'redis'));
		//	$redis->auth(C('DATA_REDIS_AUTH'));
			if(!S($username.C('KEY_POSTFIX'),md5($key),C('KEY_EXPIRE'))){
				$data=array('err_code'=>1104,'err_msg'=>'登录异常，请重新登录');
				$this->ajaxReturn($data,'JSON');
			}
			$user[0]['key']=S($username.C('KEY_POSTFIX'));

			//更改经纬度
			updateLngLat($username,$lng,$lat);

			$renovationWhere['user_id']=$user[0]['user_id'];
			$renovation=M('user_renovation_conf')->where($renovationWhere)->select()?true:false;

			//查询装修配置
			$repairWhere['user_id']=$user[0]['user_id'];
			$repair=M('user_repair_conf')->where($repairWhere)->select()?true:false;

			//查询供应商配置
			$supplyWhere['user_id']=$user[0]['user_id'];
			$supply=M('user_supply_commodity')->where($supplyWhere)->select()?true:false;

			$user[0]['renovation']=$renovation;
			$user[0]['repair']=$repair;
			$user[0]['supply']=$supply;

			//更改online状态
			$data['online']=1;
			$data['identity']=$role;
			M('user')->where("phone='$username'")->save($data);
			$user[0]['online']=1;
			$user[0]['identity']="$role";
			$this->log($username);
			$realwhere['user_id']=$user[0]['user_id'];
			$real=M('user_real_info')->where($realwhere)->find();
			$user[0]['id_name']='';
            empty($real)==false and $user[0]['id_name']=$real['id_name'];
			//返回待服务状态中的订单ID
			if($role==1){
				$status = '1,2,-3';
				$maps['user_id'] = $user[0]['user_id'];
				$maps['status'] = array('in',$status);
				$order_id = M('repair_order')->field('repair_order_id')->where($maps)->select();
				$handleOrder = '';
				if($order_id){
					$handleOrder = count($order_id);
				}
				$user[0]['handleOrder'] = $handleOrder;
			}elseif($role==2){
				$status = '1,2,-3';
				$maps['worker_user_id'] = $user[0]['user_id'];
				$maps['status'] = array('in',$status);
				$order_id = M('repair_order')->field('repair_order_id')->where($maps)->select();
				$handleOrder = '';
				if($order_id) {
					$handleOrder = count($order_id);
				}
				$user[0]['handleOrder'] = $handleOrder;
			}
			$data=array('err_code'=>200,'err_msg'=>$user);
			$this->ajaxReturn($data,'JSON');
		}else{
			$data=array('err_code'=>1103,'err_msg'=>'密码或账户错误');
			$this->ajaxReturn($data,'JSON');
		}
	}

	//退出登录
	public function LoginOut(){
		//解决跨域
		echoHeader();
		$username=session('user');
		M('user')->online=0;
		$status=M('user')->where("phone='$username'")->save();
		if($status===false){
			$data=array('err_code'=>403,'err_msg'=>'在线状态修改失败');
			$this->ajaxReturn($data,'JSON');
		}
		S(array('type'=>'redis'));
		S($username.C('KEY_POSTFIX'),null);
		session('user',null);
		$data=array('err_code'=>200,'err_msg'=>'退出成功');
		$this->ajaxReturn($data,'JSON');
	}

	//发送注册短信验证码
		public function getVerify(){
			//解决跨域
			echoHeader();
		$phone=I('post.phone','');
		$type=I('post.type',null);  //1是注册，2是登录，3是忘记密码,4是短信登录
		if(!preg_match("/^1[3-9][0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/",$phone)){
			//验证不通过
			$data=array('err_code'=>1002,'err_msg'=>'请正确输入手机号码');
			$this->ajaxReturn($data,'JSON');
		}
			$where['phone']=$phone;
			$phone_exist=M('user')->where($where)->find();
			if($type==1 && $phone_exist){
				$data=array('err_code'=>1301,'err_msg'=>'用户已注册');
				$this->ajaxReturn($data,'JSON');
			}

			if($type==2 || $type==3 || $type==4){
				$where['phone']=$phone;
				if(!$phone_exist){
					$data=array('err_code'=>1101,'err_msg'=>'用户未注册');
					$this->ajaxReturn($data,'JSON');
				}
			}
		$rand=getRandChar(4);
		$url=C('MSG_CONFIG')['url'];

		$message=str_replace(C('MSG_CONFIG')['replace'],$rand , C('MSG_CONFIG')['content']);
		$post_data = array (
				"method" => "Submit",
				"account" => C('MSG_CONFIG')['account'],
				"password" => C('MSG_CONFIG')['password'],
				'mobile'=>$phone,
				'content'=>$message,
				'format'=>'json'
		);
		//curl模拟发送post请求
		$response=http($url,$post_data,'post');
		//记录验证码
		S(array('type'=>'redis'));
		$message=$rand;
		switch ($type) {
			case 1:
				S($phone.'R',$message,120);//注册
				break;
			case 2:
				S($phone.'L',$message,120);//登录
				break;
			case 3:
				S($phone.'F',$message,120);//忘记密码
				break;
			case 4:
				S($phone.'M',$message,120);//短信登录
				break;
		}

		$response=json_decode($response);
		$data=array('err_code'=>$response->code,'err_msg'=>$response->msg);
		$this->ajaxReturn($data,'JSON');

	}


	//注册
	public function register(){
		//解决跨域
		echoHeader();
		$username=I('post.phone','');
		$phone=I('post.phone','');
		$yanzh=I('post.yanzh','');
		$role=I('post.role','1');
		$password=I('post.password','',md5);
		$type=I('post.type','');
		$work=I('post.work','');
		$invite=I('post.invite','');
		$work_time=I('post.work_time','');
		$lng=I('post.lng','');    //经度
		$lat=I('post.lat','');    //纬度
		S(array('type'=>'redis'));
		$messaggeVerify=S($phone.'R');



		if(!preg_match("/^1[3-9][0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/",$phone)){
			//不验证通过
			$data=array('err_code'=>1002,'err_msg'=>'请正确输入手机号码');
			$this->ajaxReturn($data,'JSON');
		}


		if(!$phone){
			$data=array('err_code'=>1001,'err_msg'=>'手机号码不能为空');
			$this->ajaxReturn($data,'JSON');
		}

		if(!$yanzh){
			$data=array('err_code'=>1001,'err_msg'=>'验证码不能为空');
			$this->ajaxReturn($data,'JSON');
		}

		if(!$messaggeVerify){
			$data=array('err_code'=>1002,'err_msg'=>'验证码超时，请重新发送');
			$this->ajaxReturn($data,'JSON');
		}

		if($yanzh!=$messaggeVerify){
			$data=array('err_code'=>1002,'err_msg'=>'验证码错误，请重新发送');
			$this->ajaxReturn($data,'JSON');
		}


		if(!$password){
			$data=array('err_code'=>1001,'err_msg'=>'密码不能为空');
			$this->ajaxReturn($data,'JSON');
		}
		if(!$work && $type==2){
			$data=array('err_code'=>1001,'err_msg'=>'就职单位不能为空');
			$this->ajaxReturn($data,'JSON');
		}




		$user=M('user');
		$map['phone']=$phone;
		$map['status']=0;
		$is_exist=$user->where($map)->select();
		if($is_exist){
			$data=array('err_code'=>403,'err_msg'=>'手机号码已存在');
			$this->ajaxReturn($data,'JSON');
		}
		//检查用户名是否存在
		/*$where['user_name']=$username;
		$where['status']=0;
		$is_exist=$user->where($where)->select();

		if($is_exist){
			$data=array(code=>403,msg=>'用户名已存在');
			$this->ajaxReturn($data,'JSON');
		}*/


        $sql['user_name']=substr($username,-4);
        $sql['phone']=$phone;
        $sql['role']=$role;
        $sql['lng']=$lng;
        $sql['lat']=$lat;
		$random=getRandChar(5);
		$sql['random']=$random;
		$sql['login_password']=md5($password.$random);
		$sql['work_addr']=$work;
		$sql['work_time_id']=$work_time;
		$sql['type']=$type;
		$sql['last_login_time']=time();
		$sql['add_time']=time();

		if($id=$user->add($sql)){
			$userMoneyData=array();
			//var_dump($id);exit;
			$userMoneyData["user_id"]=$id;
			//$userMoneyData["status"]=1;
			M('UserMoney')->add($userMoneyData);

			$where['user_id']=$id;
			$data=$user->where($where)->field('user_face,user_id,user_name,phone,online,role,total,frozen_total,is_real,identity,is_listen,user_status,master_status')->select();
			if(empty($data) || $data[0]['status']==2){
				$data=array('err_code'=>1102,'err_msg'=>'黑名单');
				$this->ajaxReturn($data,'JSON');
			}
			$data[0]['user_name']=substr($username,-4);
			if($invite){
				//邀请码添加
				$inw['invite']=$invite;
				$invite_exist=M('user')->where($inw)->find();

				//检查邀请码用户存不存在
				if(!empty($invite_exist)){
					$iw['user_id']=$invite_exist['user_id'];
						$in=M('invite')->where($iw)->find();
					//检查邀请码表有没存在邀请码记录
					if($in){
						$str=$in['share_userid']?$in['share_userid'].','.$id:$id;
						$sa['share_userid']=$str;
						M('invite')->where($iw)->save($sa);
					}else{
						$indata['share_userid']=$id;
						$indata['user_id']=$invite_exist['user_id'];
						$indata['add_time']=time();
						M('invite')->where($iw)->add($indata);
					}

			}
			}
			$data=array('err_code'=>200,'err_msg'=>$data);
			$this->ajaxReturn($data,'JSON');
		}else{
			$data=array('err_code'=>403,'err_msg'=>'注册失败');
			$this->ajaxReturn($data,'JSON');
		}
	}



    //修改密码
	public function updatePassword(){
		//解决跨域
		echoHeader();
		$phone=I('post.phone','');
		$key=I('post.key','');
		$oldPassword=I('post.oldpassword','',md5);
		$newPassword=I('post.newpassword','',md5);
		$againPassword=I('post.againpassword','',md5);
		$userStatus=verifyKey($phone,$key);

		if(empty($key)){
			$data=array('err_code'=>1003,'err_msg'=>'用户登录异常');
			$this->ajaxReturn($data,'JSON');
		}

		/*if(!$userStatus){
			$data=array('err_code'=>1003,'err_msg'=>'用户状态出错');
			$this->ajaxReturn($data,'JSON');
		}*/

		if($newPassword!=$againPassword){
			$data=array('err_code'=>1003,'err_msg'=>'两次新密码不一致');
			$this->ajaxReturn($data,'JSON');
		}

		if(empty($oldPassword)){
			$data=array('err_code'=>1001,'err_msg'=>'旧密码不能为空');
			$this->ajaxReturn($data,'JSON');
		}

		if(empty($newPassword)){
			$data=array('err_code'=>1001,'err_msg'=>'新密码不能为空');
			$this->ajaxReturn($data,'JSON');
		}

		$where['phone']=$phone;
		$user=M('user');
		$password=$user->where($where)->field(array(0=>'login_password',1=>'random',2=>'user_status',3=>'master_status'))->select();
		if($password[0]['user_status'] == 1 || $password[0]['master_status'] == 1){
			$data=array('err_code'=>403,'err_msg'=>'用户已被锁定');
			$this->ajaxReturn($data,'JSON');
		}
		$oldPassword=md5($oldPassword.$password[0]['random']);
		if($oldPassword===$password[0]['login_password']){
			$data['login_password']=md5($newPassword.$password[0]['random']);
			if($user->where($where)->save($data)===false){
				$data=array('err_code'=>403,'err_msg'=>'修改失败');
				$this->ajaxReturn($data,'JSON');
			}else{
				$data=array('err_code'=>200,'err_msg'=>'修改成功');
				$this->ajaxReturn($data,'JSON');
			}
		}else{
			$data=array('err_code'=>403,'err_msg'=>'密码错误');
			$this->ajaxReturn($data,'JSON');
		}
	}




	//忘记密码
	public function forgotPass(){
		//解决跨域
		echoHeader();
		$phone=I('post.phone');
		$verify=I('post.verify');
		$password=I('post.password','','md5');
		$againPassword=I('post.againpassword','','md5');
		if(empty($phone) || empty($verify)){
			$data=array('err_code'=>1001,'err_msg'=>'缺失参数或者登录超时');
			$this->ajaxReturn($data,'JSON');
		}

		if($password!=$againPassword){
			$data=array('err_code'=>1002,'err_msg'=>'2次密码不相同');
			$this->ajaxReturn($data,'JSON');
		}

        S(array('type'=>'redis'));
		$userVerify=S($phone.'F');
		if($verify!=$userVerify){
			$data=array('err_code'=>1002,'err_msg'=>'验证码错误');
			$this->ajaxReturn($data,'JSON');
		}
		$where['phone']=$phone;
		$passwd=M('user')->where($where)->limit(1)->select();
		if($passwd[0]['user_status'] == 1 || $passwd[0]['master_status'] == 1){
			$data=array('err_code'=>403,'err_msg'=>'用户已被锁定');
			$this->ajaxReturn($data,'JSON');
		}
		$map['login_password']=md5($password.$passwd[0]['random']);
		if(M('user')->where($where)->save($map)===false){
			S($phone,null);
			$data=array('err_code'=>403,'err_msg'=>'修改失败');
			$this->ajaxReturn($data,'JSON');
		}else{
			S($phone,null);
			$data=array('err_code'=>200,'err_msg'=>'修改成功');
			$this->ajaxReturn($data,'JSON');
		}
	}




	//短信登录
	public function messageLogin(){
		//解决跨域
		echoHeader();
		$phone=I('post.phone','');
		$verife=I('post.verify','');
		$role=I('post.role','','int');
		if(empty($phone) || empty($verife)){
			$data=array('err_code'=>1001,'err_msg'=>'密码或验证码不能为空');
			$this->ajaxReturn($data,'JSON');
		}

		if(empty($phone)){
			$data=array('err_code'=>403,'err_msg'=>'手机号码不能为空');
			$this->ajaxReturn($data,'JSON');
		}

		$pw['phone']=$phone;
		$user=M('user')->where($pw)->find();


        if(empty($user)){
			$data=array('err_code'=>403,'err_msg'=>'手机号码未注册');
			$this->ajaxReturn($data,'JSON');
		}

		if($role==2 && $user['is_real']==0){
			$data=array('err_code'=>1107,'err_msg'=>'师傅未认证');
			$this->ajaxReturn($data,'JSON');
		}

		if($role==2 && $user['is_real']==2){
			$data=array('err_code'=>1108,'err_msg'=>'实名认证中');
			$this->ajaxReturn($data,'JSON');
		}
		if($role==2 && $user['is_real']==3){
			$data=array('err_code'=>1109,'err_msg'=>'审核未通过');
			$this->ajaxReturn($data,'JSON');
		}

		if($role==1 &&($user['user_status']==1 || $user['user_status']==3 )){
			$data=array('err_code'=>1102,'err_msg'=>'已被锁定');
			$this->ajaxReturn($data,'JSON');
		}

		if($role==2 &&($user['master_status']==1 || $user['master_status']==3 )){
			$data=array('err_code'=>1102,'err_msg'=>'已被锁定');
			$this->ajaxReturn($data,'JSON');
		}

		S(array('type'=>'redis'));
		$userVerify=S($phone.'M');
		if($verife!=$userVerify){
			$data=array('err_code'=>403,'err_msg'=>'验证码错误');
			$this->ajaxReturn($data,'JSON');
		}else{
			$key=$phone.C('KEY_POSTFIX').time();
			if(!S($phone.C('KEY_POSTFIX'),md5($key),C('KEY_EXPIRE'))){
				$data=array('err_code'=>403,'err_msg'=>'登录异常，请重新登录');
				$this->ajaxReturn($data,'JSON');
			}
			//更改online状态
			S($phone.'M',null);
			$data['online']=1;
			$data['identity']=$role;
			M('user')->where("phone='$phone'")->save($data);
			$where['phone']=$phone;
			$user=M('user')->where($where)->select();
			$this->log($phone);
			$realwhere['user_id']=$user[0]['user_id'];
			$real=M('user_real_info')->where($realwhere)->find();
			$user[0]['id_name']='';
			empty($real)==false and $user[0]['id_name']=$real['id_name'];
			$user[0]['key']=S($phone.C('KEY_POSTFIX'));
			$data=array('err_code'=>200,'err_msg'=>$user);
			$this->ajaxReturn($data,'JSON');
		}

	}

	/**
	 * 用户登录时间
	 */

	public function log($phone){
		$log = M('user')->field('user_id')->where('phone = '.$phone)->find();
		$data['user_id'] = $log['user_id'];
		$data['login_time'] = time();
		$info = M('user_login_log')->add($data);

	}





}